package com.midcent.networklib.manager;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.android.volley.AuthFailureError;

import org.apache.commons.lang3.StringUtils;

import java.net.HttpURLConnection;
import java.net.URI;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import static android.R.attr.x;

/**
 * Save all information of application
 * <p/>
 * Created by xiangke on 2016/1/11.
 */
public class HttpRequestNetManager {

    private static HttpRequestNetManager ourInstance = new HttpRequestNetManager();

    public static String getBaseSessionGetUrl() {
        return baseSessionGetUrl;
    }

    public static void setBaseSessionGetUrl(String baseSessionGetUrl) {
        HttpRequestNetManager.baseSessionGetUrl = baseSessionGetUrl;
    }

    private static String baseSessionGetUrl = "https://dev.mid-cent.com:9001";

    private static String baseServerURL = "https://dev.mid-cent.com:9001";
    public static String deviceno = "";
    public static String token;

    public static HttpRequestNetManager getInstance() {
        return ourInstance;
    }

    private HttpRequestNetManager() {

    }

    public Map<String, String> getHeaders(String timestamp) throws AuthFailureError {
        String appcode = HttpRequestNetManager.getAppcode();
        String deviceno = HttpRequestNetManager.deviceno;
        String echostr = getRandomString(16);
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("deviceno", deviceno);
        headers.put("appcode", appcode);
        headers.put("echostr", echostr);
        headers.put("timestamp", timestamp);
        headers.put("signature", getSignature(deviceno, appcode, timestamp, echostr));
        headers.put("token", HttpRequestNetManager.token);
        headers.put("apiversion", HttpRequestNetManager.apiversion);
        headers.put("user-agent", "wnbmall v1.0");
        return headers;
    }

    public void setHeaders(HttpURLConnection conn, String timestamp) throws AuthFailureError {
        String appcode = HttpRequestNetManager.getAppcode();
        String deviceno = HttpRequestNetManager.deviceno;
        String echostr = getRandomString(16);
        Map<String, String> headers = new HashMap<String, String>();
        conn.setRequestProperty("deviceno", deviceno);
        conn.setRequestProperty("appcode", appcode);
        conn.setRequestProperty("echostr", echostr);
        conn.setRequestProperty("timestamp", timestamp);
        conn.setRequestProperty("signature", getSignature(deviceno, appcode, timestamp, echostr));
        conn.setRequestProperty("token", HttpRequestNetManager.token);
        conn.setRequestProperty("apiversion", HttpRequestNetManager.apiversion);
        conn.setRequestProperty("user-agent", "wnbmall v1.0");
    }

    public static String getSignature(String deviceno, String appcode, String timestamp, String echostr) {

        try {
            String[] array = new String[]{deviceno, encrypt, timestamp, appcode, echostr};
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < 5; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("count_hash_fail");
        }
    }

    //获取随机字符串
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

//    private static String baseServerURL = "https://www.mid-cent.com";
//    private static String baseServerURL = "https://cdn.mid-cent.com:9001";


    private static String getHost(String url) {
        if (!(StringUtils.startsWithIgnoreCase(url, "http://") || StringUtils
                .startsWithIgnoreCase(url, "https://"))) {
            url = "http://" + url;
        }
        String returnVal = StringUtils.EMPTY;
        try {
            URI uri = new URI(url);
            returnVal =  uri.getScheme()+"://"+uri.getHost();
        } catch (Exception e) {
        }

        return returnVal;
    }

    private static int getPort(String url) {
        if (!(StringUtils.startsWithIgnoreCase(url, "http://") || StringUtils
                .startsWithIgnoreCase(url, "https://"))) {
            url = "http://" + url;
        }
        int returnVal = 443;
        try {
            URI uri = new URI(url);
            if(uri.getPort()>0){
                returnVal = uri.getPort();
            }
        } catch (Exception e) {
        }
        return returnVal;
    }

    private static String appcode = "mall";
    private static String encrypt = "XXXXXXXXXX";


    /**
     * This is test for request
     */

    public static boolean isdebug = false;

    public static String apiversion = "2";

    public static String getHost() {

        return getHost(baseServerURL);
    }

    public static int getPort() {
        return getPort(baseServerURL);
    }

    public static String getServerHost() {
        return baseServerURL;
    }

    public static void setServerHost(String url) {
        baseServerURL = url;
    }

    public static String getAppcode() {
        return appcode;
    }

    public static void setAppcode(String packagename) {
        appcode = packagename;
    }


    /**
     * get encrypt of application
     *
     * @return
     */
    public static String getEncrypt() {
        return encrypt;
    }
}
